package com.zzyl.nursing.service.impl;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.RedisKeyConstants;
import com.zzyl.common.core.page.PageDomain;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.dto.FamilyMemberElderDto;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.vo.FamilyListVo;
import com.zzyl.nursing.vo.FamilyMemberEldVo;
import com.zzyl.nursing.vo.HealthMsgVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberElderMapper;
import com.zzyl.nursing.domain.FamilyMemberElder;
import com.zzyl.nursing.service.IFamilyMemberElderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;
/**
 * 客户老人关联Service业务层处理
 * 
 * @author koi
 * @date 2025-08-08
 */
@Service
public class FamilyMemberElderServiceImpl extends ServiceImpl<FamilyMemberElderMapper,FamilyMemberElder> implements IFamilyMemberElderService
{
    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询客户老人关联
     * 
     * @param id 客户老人关联主键
     * @return 客户老人关联
     */
    @Override
    public FamilyMemberElder selectFamilyMemberElderById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询客户老人关联列表
     * 
     * @param familyMemberElder 客户老人关联
     * @return 客户老人关联
     */
    @Override
    public List<FamilyMemberElder> selectFamilyMemberElderList(FamilyMemberElder familyMemberElder)
    {
        return familyMemberElderMapper.selectFamilyMemberElderList(familyMemberElder);
    }

    /**
     * 新增客户老人关联
     * 
     * @param familyMemberElder 客户老人关联
     * @return 结果
     */
    @Override
    public int insertFamilyMemberElder(FamilyMemberElder familyMemberElder)
    {
        return save(familyMemberElder)?1:0;
    }

    /**
     * 修改客户老人关联
     * 
     * @param familyMemberElder 客户老人关联
     * @return 结果
     */
    @Override
    public int updateFamilyMemberElder(FamilyMemberElder familyMemberElder)
    {
        return updateById(familyMemberElder)?1:0;
    }

    /**
     * 批量删除客户老人关联
     * 
     * @param ids 需要删除的客户老人关联主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberElderByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除客户老人关联信息
     * 
     * @param id 客户老人关联主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberElderById(Long id)
    {
        return removeById(id)?1:0;
    }
/**
 * 绑定家人
 * @param dto
 */
    @Override
    public void add(FamilyMemberElderDto dto) {
        //判断信息是否为空
        if ( ObjectUtils.isEmpty(dto.getIdCard())||ObjectUtils.isEmpty(dto.getName())||ObjectUtils.isEmpty(dto.getRemark()) ){
            throw new RuntimeException("信息不完整");
        }
        //判断身份证格式是否正确
        if (dto.getIdCard().length() != 18){
            throw new RuntimeException("身份证格式错误");
        }
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<Elder>()
                .eq(Elder::getIdCardNo, dto.getIdCard());
        Elder elder = elderMapper.selectOne(queryWrapper);
        if (ObjectUtils.isEmpty(elder)){
            throw new BaseException("该老人未入住");
        }
        Long userId = UserThreadLocal.getUserId();
        // 查询家庭成员与老人关系的数量,已有老人则抛异常
        Long count = familyMemberElderMapper.selectCount(
                new LambdaQueryWrapper<FamilyMemberElder>()
                        .eq(FamilyMemberElder::getFamilyMemberId, userId)
                        .eq(FamilyMemberElder::getElderId, elder.getId())
        );
        //判断是否已经绑定老人
        if (count > 0){
            throw new BaseException("该老人已经绑定");
        }
        //copy属性
        FamilyMemberElder familyMemberElder = BeanUtil.toBean(elder, FamilyMemberElder.class);
        //属性赋值
        familyMemberElder.setFamilyMemberId(userId);
        familyMemberElder.setElderId(elder.getId());
        familyMemberElder.setRemark(dto.getRemark());
        save(familyMemberElder);
    }


    /**
     * 1.2 查询家人列表
     * 接口地址:/member/user/my
     * 请求方式:GET
     * 请求参数: 无
     */
    @Override
    public List<FamilyMemberEldVo> findFamilyMemberList() {
        //获取当前用户ID
        Long userId = UserThreadLocal.getUserId();
        List<FamilyMemberEldVo> list = familyMemberElderMapper.selectByFamilyMemberId(userId);
        List<FamilyMemberElder> familyMemberElderList= familyMemberElderMapper.selectList(Wrappers.<FamilyMemberElder>lambdaQuery()
                .eq(FamilyMemberElder::getFamilyMemberId,userId));
        list.forEach(item->{
            familyMemberElderList.forEach(familyMemberElder->{
                item.setId(familyMemberElder.getId());
            });
        });
        return list;
    }

    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    /**
     * 分页查询家人列表
     * 接口地址:/member/user/my
     * 请求方式:GET
     * 请求参数: 无
     */
    @Override
    public List<FamilyListVo> listByPage(PageDomain pageDomain) {
        Long familyMemberId = UserThreadLocal.getUserId();
        List<FamilyListVo> listVos = familyMemberMapper.listByPage(familyMemberId);
        return listVos;
    }

    @Override
    public List<HealthMsgVo> queryServiceProperties(String iotId) {
        Object data = redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA,iotId);
        if (ObjectUtil.isEmpty( data)){
            throw new BaseException("设备数据不存在");
        }
        List<DeviceData> deviceDataList = JSONUtil.toList(data.toString(), DeviceData.class);
        List<HealthMsgVo> voList = new ArrayList<>();
        deviceDataList.forEach(deviceData -> {
            HealthMsgVo vo = new HealthMsgVo();
            vo.setFunctionId(deviceData.getFunctionId()) ;
            vo.setEventTime(String.valueOf(deviceData.getAlarmTime()));
            vo.setValue(deviceData.getDataValue());
            voList.add(vo) ;
        });
        return voList;
    }
}
